package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.RecommendAdapter;
import elitech.vietnam.myfashion.fragment.DetailFragment;
import elitech.vietnam.myfashion.widgets.ExpandableHeightGridView;

public class RecommendGroupView extends LinearLayout {
	private MainActivity mContext;
	private Product mProduct;
	private ExpandableHeightGridView mGridView;
	private TextView mTitle;
	private RecommendAdapter mAdapter;
	private ArrayList<Product> mListRecommend = new ArrayList<Product>();
	public RecommendGroupView(MainActivity context, Product product) {
		super(context);
		this.mProduct = product;
		this.mContext = context;
		
		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(inflater != null){
            inflater.inflate(R.layout.recommends, this);
        }
		
		mGridView = (ExpandableHeightGridView) findViewById(R.id.recommend_grid);
		mAdapter = new RecommendAdapter(mContext, mGridView.getId(), mListRecommend);
		mGridView.setAdapter(mAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (mContext.mDetailFragment == null)
					mContext.mDetailFragment = new DetailFragment();
				if (!mContext.mDetailFragment.isAdded()) {
					mContext.mDetailFragment.setProduct(mListRecommend.get(arg2));
					mContext.replaceFragment(mContext.mDetailFragment, true);
				}else{
					mContext.mDetailFragment.view.ChangeProduct(mListRecommend.get(arg2));
				}
			}
		});
		
		mTitle = (TextView) findViewById(R.id.recommend_txtRecommend);
		GetRecommend();
		
	}
	
	private void GetRecommend(){
		new CallServiceTask() {
			private ArrayList<Product> rs = new ArrayList<Product>();

			public void work() {
				try {
					int id = (mContext.mUser == null)? -1: mContext.mUser.Id;
					rs = service.getProductRecommended(mProduct.Id, id);
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				if(rs.size()!=0)
					mTitle.setVisibility(View.VISIBLE);
				
				mListRecommend.addAll(rs);
				mAdapter.notifyDataSetChanged();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	
}
